package com.example.onlinemusic.service;

import com.example.onlinemusic.mapper.UserMapper;
import com.example.onlinemusic.model.User;
import com.example.onlinemusic.tools.Constant;
import com.example.onlinemusic.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    public ResponseBodyMessage<User> login(@RequestParam String username, @RequestParam String password,
                                           HttpServletRequest servletRequest) {
        User user = userMapper.selectByName(username);
        if(user == null) {
            return new ResponseBodyMessage<>(-1, "用户名或密码错误", user);
        } else {
            boolean flg = bCryptPasswordEncoder.matches(password, user.getPassword());
            if (!flg) {
                return new ResponseBodyMessage<>(-1, "用户名或密码错误", user);
            }
            servletRequest.getSession().setAttribute(Constant.USERINFO_SESSION_KEY, user);
            return new ResponseBodyMessage<>(0,"登陆成功", user);
        }
    }
}
